#!/bin/bash
set -e

MYSQL_CONFIG="/opt/zbox/etc/mysql/my.cnf"
VERSION_FILE="/opt/zbox/app/zentao/VERSION"

export PATH=/opt/zbox/:$PATH
if [ "${1:0:1}" == "-" ]; then
  zbox --help
elif [ "$#" == "0" ]; then
  # if the container run firstly
  if [ ! -d "/opt/zbox" -o ! -d "/opt/zbox/app" ]; then
    echo "Installing Zentao version: ${ZENTAO_VER} ..."
    tar -zxf /tmp/zbox.tar.gz -C /opt/
    rm -rf /opt/zbox/app/zentao[ep]*
    
    if [[ "${BIND_ADDRESS}" == [fF][aA][lL][sS][eE] ]] && [ -f "${MYSQL_CONFIG}" ]; then
      sed -e 's/^bind-address.*$/bind-address            = 0.0.0.0/' -i ${MYSQL_CONFIG}
    fi

  elif [ -f "${VERSION_FILE}" -a `cat ${VERSION_FILE}` != ${ZENTAO_VER} ]; then
    CURRENT_VER=`cat ${VERSION_FILE}`
    echo -e "The Zentao need update.\n  Old version: $CURRENT_VER \n  New version: $ZENTAO_VER"
    # upgrade zentao version
    echo "Backuping config / my.php / upload ..."
    cp /opt/zbox/app/zentao/config/my.php /opt/zbox/app/

    cp -r /opt/zbox/app/zentao/www/data/upload /opt/zbox/app/
    #创建资源目录、数据库备份
    echo "开始备份资源目录、数据库文件"
    time=$(date "+%Y-%m-%d_%H_%M_%S")
    if [ ! -d "/opt/zbox/backUp/" ];then
      mkdir -p /opt/zbox/backUp/
    else
      echo "备份文件夹已经存在，跳过创建"
    fi
    echo "开始备份禅道资源文件夹（/opt/zbox/app/zentao）"
    tar -czPp -f /opt/zbox/backUp/zentao.$time.tar.gz /opt/zbox/app/zentao
    echo "开始备份禅道开源版数据库(/opt/zbox/data)"
    tar -czPp -f /opt/zbox/backUp/zentao.mysql.$time.tar.gz /opt/zbox/data
    echo "$(pwd)"
    #若升级文件存在则进入下面的步骤
    if [ ! -f "/tmp/zbox.tar.gz" ];then
      rm -rf /opt/zbox/app/zentao

      echo "Upgrading..."
      tar -zxf /tmp/zbox.tar.gz -C /tmp/
      mv /tmp/zbox/app/zentao /opt/zbox/app/
      mv /tmp/upgrade.php /opt/zbox/app/zentao/www/
      chmod 664 /opt/zbox/app/zentao/www/upgrade.php
      rm -rf /opt/zbox/tmp/apache/httpd.pid /tmp/*

      echo "Restoring config / my.php / upload ..."
      mv /opt/zbox/app/my.php /opt/zbox/app/zentao/config/my.php
      rm -rf /opt/zbox/app/zentao/www/data/upload
      mv /opt/zbox/app/upload /opt/zbox/app/zentao/www/data/
      touch /opt/zbox/app/zentao/www/ok.txt
      echo "Upgraded Zentao version to: ${ZENTAO_VER}\nPlease visit your Zentao website to complete the upgrade task."
      else
        echo "升级文件不存在：/tmp/zbox.tar.gz不存在"
        fi
  fi
  
  # add apache http password for adminer
  if [ -n "${ADMINER_USER}"  -a -n "${ADMINER_PASSWD}" ]; then
    /opt/zbox/bin/htpasswd -b /opt/zbox/auth/users ${ADMINER_USER} ${ADMINER_PASSWD}
    chmod 0644 /opt/zbox/auth/users
  fi
  # compatible old version
  if [ -n "${USER}" -a -n "${PASSWD}" ]; then
    /opt/zbox/bin/htpasswd -b /opt/zbox/auth/users ${USER} ${PASSWD}
    chmod 0644 /opt/zbox/auth/users
  fi

  # add smtp server ip to hosts
  if [ -n "${SMTP_HOST}" ];then
    #IS_EXIST_SMTP_HOST=`grep "${SMTP_HOST}" /etc/hosts`
    #if [ -z "${IS_EXIST_SMTP_HOST}"];then
      echo "${SMTP_HOST}" >> /etc/hosts
    #fi
  fi

  # auto location / to /zentao/
  echo "<meta http-equiv=\"refresh\" content=\"0; url=/zentao/\" />" > /opt/zbox/app/htdocs/index.html

  # start service and health check
  cat /opt/zbox/README
  zbox start
  sleep 120
  loop=1
  while [ ${loop} -eq 1 ]
  do
    wget http://localhost/ -O /dev/null || exit 1
    sleep 30
  done
else
  exec "$@"
fi
